package com.css.ztb.service.impl;

import com.css.ztb.common.ShiroConstants;
import com.css.ztb.domain.SysUser;
import com.css.ztb.service.PasswordService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author shipeilei
 * @date 2020-6-28 19:40:33
 * @desc desc
 */
@Service
public class PasswordServiceImpl implements PasswordService {
    @Value(value = "${user.password.maxRetryCount}")
    private String maxRetryCount;

    @Autowired
    private CacheManager cacheManager;

    private Cache<String, AtomicInteger> loginRecordCache;

    @PostConstruct
    public void init()
    {
        loginRecordCache = cacheManager.getCache(ShiroConstants.LOGINRECORDCACHE);
    }

    @Override
    public void validate(SysUser user, String password) {
        String loginName = user.getLoginName();
        AtomicInteger retryCount = loginRecordCache.get(loginName);
        if (null == retryCount) {
            retryCount = new AtomicInteger(0);
        }
        int count = Integer.parseInt(maxRetryCount);
        if (retryCount.incrementAndGet() > count) {
            throw new AuthenticationException("失败次数超过5次");
        }
        if (!matches(user, password)) {
            throw new AuthenticationException("用户密码错误");
        } else {
            clearLoginRecordCache(loginName);
        }
    }

    public boolean matches(SysUser user, String newPassword) {
        return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
    }

    public String encryptPassword(String username, String password, String salt) {
        return new Md5Hash(username + password + salt).toHex();
    }

    public void clearLoginRecordCache(String username)
    {
        loginRecordCache.remove(username);
    }
}
